﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using GetWebInfo;

namespace FA
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取和讯三大报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                Statement.Parse(this.textBox1.Text, this.checkBox1.Checked, this.checkBox2.Checked, this.checkBox3.Checked, this.checkBox4.Checked, this.textBox2.Text, this.textBox3.Text, this.checkBox5.Checked);
                MessageBox.Show("OK!");
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(string.Format("Message:{0}, StackTrace:{1}", exp.Message, exp.StackTrace));
            }
        }

        /// <summary>
        /// 将三大报表中的temp整理好
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {
            try
            {
                Statement.RePackTempToJson(this.textBox1.Text);
                MessageBox.Show("OK!");
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(string.Format("Message:{0}, StackTrace:{1}", exp.Message, exp.StackTrace));
            }
        }

        /// <summary>
        /// 获取新浪价格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                SharePrice.Parse(this.textBox1.Text, this.textBox2.Text, this.textBox3.Text, this.checkBox5.Checked);
                MessageBox.Show("ok!");
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(string.Format("Message:{0}, StackTrace:{1}", exp.Message, exp.StackTrace));
            }
        }

        /// <summary>
        /// 通过和讯网页，获取派现金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button11_Click(object sender, EventArgs e)
        {
            try
            {
                Dividend.Parse(this.textBox1.Text);
                MessageBox.Show("ok!");
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(string.Format("Message:{0}, StackTrace:{1}", exp.Message, exp.StackTrace));
            }
        }

        /// <summary>
        /// 派现金额融入报表中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        {
            try
            {
                Dividend _de = Dividend.Load(this.textBox1.Text);
                _de.DividendInStatements(this.textBox1.Text);
                MessageBox.Show("ok!");
            }
            catch (System.Exception exp)
            {
                MessageBox.Show(string.Format("Message:{0}, StackTrace:{1}", exp.Message, exp.StackTrace));
            }
        }



        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            IndustrialStatements _ffs = _fsList[int.Parse(this.comboBox1.SelectedItem.ToString())];
            _ffs.Non_recurring_Gains_and_Losses = decimal.Parse(this.textBox8.Text.Replace(",", ""));
            _ffs.Dividends = decimal.Parse(this.textBox9.Text.Replace(",", ""));
            _ffs.Interest_Expense = decimal.Parse(this.textBox10.Text.Replace(",", ""));
            _ffs.Interest_Income = decimal.Parse(this.textBox18.Text.Replace(",", ""));
            _ffs.The_Number_of_Employees = decimal.Parse(this.textBox11.Text.Replace(",", ""));
            _ffs.Professional_staff_structure = this.textBox17.Text.Replace(",", "");
            _ffs.The_Number_of_Retired_Employees = decimal.Parse(this.textBox12.Text.Replace(",", ""));
            _ffs.Managers_Before_The_Three_Annual_Salary = decimal.Parse(this.textBox13.Text.Replace(",", ""));
            _ffs.The_Top_Three_Holdings_Before_The_Manager = decimal.Parse(this.textBox14.Text.Replace(",", ""));
            _ffs.Depreciation = decimal.Parse(this.textBox7.Text.Replace(",", ""));
            _ffs.Amortization = decimal.Parse(this.textBox15.Text.Replace(",", ""));

            _ffs.Save(this.comboBox1.SelectedItem.ToString(), this._stockCode);

            MessageBox.Show("OK");
        }

        /// <summary>
        /// 选择需要完善的标的
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            this._stockCode = this.textBox1.Text;

            _fsList.Clear();
            this.comboBox1.Items.Clear();
            this._directoryPath = string.Format(@"{0}\{1}", System.AppDomain.CurrentDomain.BaseDirectory, _stockCode);
            DirectoryInfo _di = new DirectoryInfo(this._directoryPath);
            FileInfo[] _files = _di.GetFiles();

            SortedList<int, int> _iyears = new SortedList<int, int>();
            foreach (FileInfo fi in _files)
            {
                //目前只能完善年的
                if (fi.Extension == ".json" &&
                    fi.Name.Length == 9)
                {
                    IndustrialStatements _fs = (IndustrialStatements)Statement.Load(fi.FullName);
                    int _year = int.Parse(fi.Name.Substring(0, 4));
                    _fsList.Add(_year, _fs);
                    _iyears.Add(_year, 0);
                }
            }

            foreach (KeyValuePair<int, int> kvp in _iyears)
            {
                this.comboBox1.Items.Add(kvp.Key);
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            IndustrialStatements _ffs = _fsList[int.Parse(this.comboBox1.SelectedItem.ToString())];
            this.textBox8.Text = _ffs.Non_recurring_Gains_and_Losses.ToString();
            this.textBox9.Text = _ffs.Dividends.ToString();
            this.textBox10.Text = _ffs.Interest_Expense.ToString();
            this.textBox18.Text = _ffs.Interest_Income.ToString();
            this.textBox11.Text = _ffs.The_Number_of_Employees.ToString();
            this.textBox12.Text = _ffs.The_Number_of_Retired_Employees.ToString();
            this.textBox13.Text = _ffs.Managers_Before_The_Three_Annual_Salary.ToString();
            this.textBox14.Text = _ffs.The_Top_Three_Holdings_Before_The_Manager.ToString();
            this.textBox7.Text = _ffs.Depreciation.ToString();
            this.textBox15.Text = _ffs.Amortization.ToString();
            this.textBox6.Text = "";
            if (_ffs.Professional_staff_structure != null)
            {
                this.textBox17.Text = _ffs.Professional_staff_structure.ToString();
            }
            else
            {
                this.textBox17.Text = "";
            }
        }

        /// <summary>
        /// 获取原始财务数据（年）  \n
        /// 并直接将数据保存到剪贴板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            this._stockCode = this.textBox1.Text;
            DirectoryInfo _di = new DirectoryInfo(string.Format(@"{0}\{1}\", System.AppDomain.CurrentDomain.BaseDirectory, this._stockCode));
            FileInfo[] _files = _di.GetFiles();
            SortedList<int, Statement> _fsList = new SortedList<int, Statement>();

            foreach (FileInfo fi in _files)
            {
                if (Regex.IsMatch(fi.Name, @"^\d{4}.json$", RegexOptions.None))
                {
                    Statement _fs = Statement.Load(fi.FullName);
                    _fsList.Add(int.Parse(fi.Name.Substring(0, fi.Name.IndexOf("."))), _fs);
                }
            }

            string _str = ""; string _byear = ""; string _eyear = "";
            foreach (KeyValuePair<int, Statement> kvp in _fsList)
            {
                if (_byear == "")
                {
                    _byear = kvp.Key.ToString();
                }
                _eyear = kvp.Key.ToString();
                _str += string.Format("{0}\t", kvp.Key);
                _str += kvp.Value.ToString();
            }

            Clipboard.SetData(DataFormats.Text, (Object)_str);

            MessageBox.Show(string.Format("Code:{2},OK,BeginYear:{0},EndYear:{1}.", _byear, _eyear, _stockCode));
        }

        /// <summary>
        /// 获取原始财务数据（季）  \n
        /// 并直接将数据保存到剪贴板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this._stockCode = this.textBox1.Text;
            DirectoryInfo _di = new DirectoryInfo(string.Format(@"{0}\{1}\", System.AppDomain.CurrentDomain.BaseDirectory, this._stockCode));
            FileInfo[] _files = _di.GetFiles();
            SortedList<int, Statement> _fsList = new SortedList<int, Statement>();

            foreach (FileInfo fi in _files)
            {
                if (Regex.IsMatch(fi.Name, @"^\d{5}.json$", RegexOptions.None))
                {
                    Statement _fs = Statement.Load(fi.FullName);
                    _fsList.Add(int.Parse(fi.Name.Substring(0, fi.Name.IndexOf("."))), _fs);
                }
            }

            string _str = ""; string _byear = ""; string _eyear = "";
            foreach (KeyValuePair<int, Statement> kvp in _fsList)
            {
                if (_byear == "")
                {
                    _byear = kvp.Key.ToString();
                }
                _eyear = kvp.Key.ToString();
                _str += string.Format("{0}\t", kvp.Key);
                _str += kvp.Value.ToString();
            }

            Clipboard.SetData(DataFormats.Text, (Object)_str);

            MessageBox.Show(string.Format("Code:{2},OK,BeginYear:{0},EndYear:{1}.", _byear, _eyear, _stockCode));
        }

        /// <summary>
        /// 获取每年平均、最大、最小市值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            this._stockCode = this.textBox1.Text;
            DirectoryInfo _di = new DirectoryInfo(string.Format(@"{0}\{1}\", System.AppDomain.CurrentDomain.BaseDirectory, this._stockCode));
            FileInfo[] _files = _di.GetFiles();

            MarketCapital _marketCapital = new MarketCapital(SharePrice.Load(_stockCode), Split.Load(_stockCode));
            SortedList<int, decimal> _avgv = _marketCapital.GetAvgValues;
            SortedList<int, decimal> _maxv = _marketCapital.GetMaxValues;
            SortedList<int, decimal> _minv = _marketCapital.GetMinValues;

            string _str = ""; string _byear = ""; string _eyear = "";
            foreach (KeyValuePair<int, decimal> kvp in _marketCapital.GetAvgValues)
            {
                if (_byear == "")
                {
                    _byear = kvp.Key.ToString();
                }
                _eyear = kvp.Key.ToString();

                _str += string.Format("{0}\t{1}\t{2}\t\r\n", _avgv[kvp.Key], _maxv[kvp.Key], _minv[kvp.Key]);
            }

            Clipboard.SetData(DataFormats.Text, (Object)_str);
            MessageBox.Show(string.Format("Code:{2},OK,BeginYear:{0},EndYear:{1}.", _byear, _eyear, _stockCode));
        }

        /// <summary>
        /// 长期PB（按季度）PE、PS（按年）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            this._stockCode = this.textBox1.Text;
            DirectoryInfo _di = new DirectoryInfo(string.Format(@"{0}\{1}\", System.AppDomain.CurrentDomain.BaseDirectory, this._stockCode));
            FileInfo[] _files = _di.GetFiles();
            SortedList<int, Statement> _fsList = new SortedList<int, Statement>();

            foreach (FileInfo fi in _files)
            {
                if (fi.Extension == ".json")
                {
                    Statement _fs = Statement.Load(fi.FullName);
                    _fsList.Add(int.Parse(fi.Name.Substring(0, fi.Name.IndexOf("."))), _fs);
                }
            }

            SharePrice _sp = SharePrice.Load(_stockCode);
            FinancialAnalysis _fa = new FinancialAnalysis(_fsList, _sp, Split.Load(_stockCode), decimal.Parse(this.textBox16.Text));

            SortedList<DateTime, decimal> _price = _sp.Prices;
            SortedList<DateTime, ulong> _shares = _fa.MarketCapital.Shares;
            SortedList<DateTime, decimal> _makcap = _fa.MarketCapital.Capitals;
            SortedList<DateTime, decimal> _pb = _fa.PB_Static_AllValue;
            SortedList<DateTime, decimal> _ps = _fa.PS_Static_Net_AllValue;
            SortedList<DateTime, decimal> _pe = _fa.PE_Static_Net_AllValue;
            SortedList<DateTime, decimal> _pbpe = _fa.PB_Multi_PE_Static_AllValue;
            //SortedList<DateTime, decimal> _ey = _fa.Earnings_Yield_Static_Net_AllValue;
            //SortedList<DateTime, decimal> _rc = _fa.Return_on_Cash_Static_Net_AllValue;
            //SortedList<DateTime, decimal> _cr = _fa.Cash_Return_Static_Net_AllValue;
            //SortedList<DateTime, decimal> _dy = _fa.Dividend_Yield_Static_AllValue;

            //增加最小PB、05年开始的最小PB、05年开始的平均PB、最大PB、05年开始的最大PB
            //增加最小PE、05年开始的最小PE、05年开始的平均PE、最大PE、05年开始的最大PE
            int _zeroFiveYearBegin = 0;
            foreach (KeyValuePair<DateTime, decimal> kvp in _sp.Prices)
            {
                _zeroFiveYearBegin++;
                if (kvp.Key.Year > 2005 ||
                    kvp.Key.Year == 2005)
                {
                    break;
                }
            }
            string _strMAXandMinPB = string.Format("=MIN(F:F)\t=MIN(F{0}:F99999)\t=AVERAGE(F{0}:F99999)\t=MAX(F:F)\t=MAX(F{0}:F99999)\r\n", _zeroFiveYearBegin + 1);
            string _strMAXandMinPE = string.Format("=MIN(G:G)\t=MIN(G{0}:G99999)\t=AVERAGE(G{0}:G99999)\t=MAX(G:G)\t=MAX(G{0}:G99999)\r\n", _zeroFiveYearBegin + 1);
            string _str = string.Format("Datetime\tPrice\tShares\tMarketCap\tNetAsserts\tPB\tPE\tPS\tPE*PB\tMIN\tMIN(05)\tAVERAGE(05)\tMAX\tMAX(05)\r\n");
            string _byear = ""; string _eyear = "";

            decimal _netAsserts = 0;
            int i = 0;
            foreach (KeyValuePair<DateTime, decimal> kvp in _sp.Prices)
            {
                if (_byear == "")
                {
                    _byear = kvp.Key.ToString();
                }
                _eyear = kvp.Key.ToString();

                decimal _jidu = Math.Ceiling((decimal.Parse(kvp.Key.Month.ToString())) / 3);
                int _jidustr = int.Parse(string.Format("{0}{1}", kvp.Key.Year, _jidu));

                if (kvp.Key.Year == 2012 && kvp.Key.Month == 3 && kvp.Key.Day == 30)
                {
                }
                if (_fsList.ContainsKey(_jidustr))
                {
                    if (_fsList[_jidustr] is IndustrialStatements)
                    {
                        _netAsserts = ((IndustrialStatements)_fsList[_jidustr]).Total_Owners_Equity;
                    }
                    else
                    {
                        _netAsserts = ((FinanceStatements)_fsList[_jidustr]).Total_Equity;
                    }
                }
                else if (_fsList.ContainsKey(kvp.Key.Year))
                {
                    if (_fsList[kvp.Key.Year] is IndustrialStatements)
                    {
                        _netAsserts = ((IndustrialStatements)_fsList[kvp.Key.Year]).Total_Owners_Equity;
                    }
                    else
                    {
                        _netAsserts = ((FinanceStatements)_fsList[kvp.Key.Year]).Total_Equity;
                    }
                }

                if (i == 0 || i == 1)
                {
                    _str += string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}",
                        kvp.Key.ToString("yyyy-MM-dd"),
                        _price[kvp.Key],
                        _shares[kvp.Key],
                        _makcap[kvp.Key],
                        _netAsserts,
                        _pb[kvp.Key],
                        _pe[kvp.Key],
                        _ps[kvp.Key],
                        _pbpe[kvp.Key],
                        i == 0 ? _strMAXandMinPB : _strMAXandMinPE);
                }
                else
                {
                    _str += string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\r\n",
                           kvp.Key.ToString("yyyy-MM-dd"),
                           _price[kvp.Key],
                           _shares[kvp.Key],
                           _makcap[kvp.Key],
                           _netAsserts,
                           _pb[kvp.Key],
                           _pe[kvp.Key],
                           _ps[kvp.Key],
                           _pbpe[kvp.Key]);
                }
                i++;
            }

            Clipboard.SetData(DataFormats.Text, (Object)_str);

            MessageBox.Show(string.Format("Code:{2},OK,Begin:{0},End:{1}.", _byear, _eyear, _stockCode));
        }


        private SortedList<int, IndustrialStatements> _fsList = new SortedList<int, IndustrialStatements>();
        private string _stockCode = "";
        private string _directoryPath = "";

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {
            IndustrialStatements _ffs = _fsList[int.Parse(this.comboBox1.SelectedItem.ToString())];
            //_ffs.Non_recurring_Gains_and_Losses = decimal.Parse(this.textBox8.Text.Replace(",", ""));
            //_ffs.Dividends = decimal.Parse(this.textBox9.Text.Replace(",", ""));
            //_ffs.Interest_Expense = decimal.Parse(this.textBox10.Text.Replace(",", ""));
            //_ffs.The_Number_of_Employees = decimal.Parse(this.textBox11.Text.Replace(",", ""));
            //_ffs.The_Number_of_Retired_Employees = decimal.Parse(this.textBox12.Text.Replace(",", ""));
            //_ffs.Managers_Before_The_Three_Annual_Salary = decimal.Parse(this.textBox13.Text.Replace(",", ""));
            //_ffs.The_Top_Three_Holdings_Before_The_Manager = decimal.Parse(this.textBox14.Text.Replace(",", ""));

            _ffs = ParsePage.Parse_Reconciliation_Of_Net_Cash_Flow_From_Operating_Activities(this.textBox6.Text, _ffs);

            //_ffs.Save(string.Format("{0}{1}", _ffs.Year, (byte)_ffs.Quarter), this._stockCode);

            MessageBox.Show("OK");
        }

        private void button10_Click(object sender, EventArgs e)
        {
            this.textBox6.Text = "";
        }


    }
}
